package com.lzx.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.reggie.common.CustomException;
import com.lzx.reggie.entity.Category;
import com.lzx.reggie.entity.Dish;
import com.lzx.reggie.entity.Setmeal;
import com.lzx.reggie.service.CategoryService;
import com.lzx.reggie.mapper.CategoryMapper;
import com.lzx.reggie.service.DishService;
import com.lzx.reggie.service.SetmealService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author 86176
 * @description 针对表【category(菜品及套餐分类)】的数据库操作Service实现
 * @createDate 2024-07-11 13:33:50
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    private final DishService dishService;
    private final SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前需要进行判断
     *
     * @param id
     */
    @Override
    public void remove(Long id) {
        //1.查询当前分类是否关联了菜品，如果关联，抛出异常
        //1.1构造一个Dish表的条件构造器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //1.2添加查询条件，根据分类id
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        //1.3判断
        int countDish = dishService.count(dishLambdaQueryWrapper);
        if (countDish > 0) {
            //关联了，抛出异常
            throw new CustomException("当前分类已关联了菜品，不能删除");
        }

        //2.查询当前分类是否关联了套餐，如果关联，抛出异常
        //1.1构造一个Dish表的条件构造器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //1.2添加查询条件，根据分类id
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        //1.3判断
        int countSetMeal = setmealService.count(setmealLambdaQueryWrapper);
        if (countSetMeal > 0) {
            //关联了，抛出异常
            throw new CustomException("当前分类已关联了套餐，不能删除");
        }

        //3.删除
        super.removeById(id);
    }
}




